<?php
namespace app\common\model;
use x\Xbase;
use Endroid\QrCode\QrCode;
use EasyWeChat\Kernel\Messages\Image;
class Userwx extends Xbase
{
    //处理文字交互事件
    public function text($message){
      // ToUserName：gh_8b24641c2fa6
      // FromUserName：oNks51OaXLmBuzepIcuXaoZJ2WNY
      // CreateTime：1536042076
      // MsgType：text
      // Content：11
      // MsgId：6597250482145518385
      $user = $this->db->query("select * from user where wx_openid=?",[$message['FromUserName']],1);
      if(!$user) return "亲, 么有找到您的信息, 程序哥哥建议您重新关注!";
      $content = trim($message['Content']);
      if(is_numeric($content)){
        $first = substr($content, 0, 1);
        $second = substr($content, 1);
        switch ($first) {
          #微信名片
          case 1:
              $img_path = $this->wxmp($user,$second);
              $media_id = $this->wxmedia($img_path,$user, true);
              return new Image($media_id);
            break;
          #宣传单页
          case 2:
              $img_path = $this->xcdt($user,$second);
              $media_id = $this->wxmedia($img_path,$user, true);
              return new Image($media_id);
            break;
          #在线文案
          case 3:
              $rs = $this->zxwa($user,$second);
              return $rs;
            break;

          default:
            // code...
            break;
        }
      }
      return "亲! 蚂蚁客服还不是很聪明呢, 以后再回答您可以吗";
    }

    //处理点击事件
    public function click($message){
      // ToUserName：gh_8b24641c2fa6
      // FromUserName：oNks51OaXLmBuzepIcuXaoZJ2WNY
      // CreateTime：1535625096
      // MsgType：event
      // Event：CLICK
      // EventKey：wdhb
      $user = $this->db->query("select * from user where wx_openid=?",[$message['FromUserName']],1);
      if(!$user) return "亲, 么有找到您的信息, 程序哥哥建议您重新关注!";
      switch ($message['EventKey']) {
        case 'tbq':
          $end_time = m('Userxiangmu','c')->check($user['id'], 1);
          if($end_time<time()){
            return "淘宝券是一个淘宝客项目,在蚂蚁帮社区可按教程申请淘宝客API. \n PC端登录社区申请 \n https://www.mayibang.co/ \n 也可点击联系客服";
          }
          $rs  = $this->db->query('select id from tbk_cat where user_id =? order by id asc', [$user['id']],1);
          if(!$rs){
              return '请到PC后台设置淘宝客API';
          }
          $img_path = $this->tbq($user);
          $media_id = $this->wxmedia($img_path,$user, true);
          return new Image($media_id);
          break;
        case 'wxmp':
          $end_time = m('Userxiangmu','c')->check($user['id'], 2);
          if($end_time<time()){
            return "微信名片转发给您的客户,您的客户可用打电话,导航等功能联系到您. 也能在名片页看到您的业务简介和店铺图片 \n PC端登录社区申请 \n https://www.mayibang.co/ \n 也可点击联系客服";
          }
          $rs  = $this->db->query('select title from wxmp where user_id =? order by sort desc, id asc', [$user['id']]);
          if(!$rs){
              return '请到PC后台设置名片';
          }else if(count($rs)>1){
              $str = "您有".count($rs)."张微信名片 \n";
              foreach($rs as $k => $v){
                $k +=1;
                $str .= "回复1{$k}:{$v['title']} \n";
              }
              return $str;
          }
          $img_path = $this->wxmp($user,1);
          $media_id = $this->wxmedia($img_path,$user, true);
          return new Image($media_id);
          break;
        case 'xcdy':
          $end_time = m('Userxiangmu','c')->check($user['id'], 3);
          if($end_time<time()){
            return "宣传单页和百度竞价页面类似, 不同的是您可以在微信里传播此单页. 如果您有招商项目需要在微信,QQ,朋友圈传播. 此项目正合适您.\n PC端登录社区申请 \n https://www.mayibang.co/ \n 也可点击联系客服";
          }
          $rs  = $this->db->query('select title from xcdy where user_id =? order by sort desc, id asc', [$user['id']]);
          if(!$rs){
              return '请到PC后台设置宣传单页';
          }else if(count($rs)>1){
              $str = "您有".count($rs)."张宣传单页 \n";
              foreach($rs as $k => $v){
                $k +=1;
                $str .= "回复2{$k}:{$v['title']} \n";
              }
              return $str;
          }
          $img_path = $this->xcdy($user,1);
          $media_id = $this->wxmedia($img_path,$user, true);
          return new Image($media_id);
          break;
        case 'zxwa':
          $end_time = m('Userxiangmu','c')->check($user['id'], 4);
          if($end_time<time()){
            return "如果您在宣传项目的时候, 苦于没有好的方式管理您提前写好的文案.  OK, 在线文案可以帮到您.\n PC端登录社区申请 \n https://www.mayibang.co/ \n 也可点击联系客服";
          }
          $rs  = $this->db->query('select title from zxwa where user_id =? order by sort desc, id asc', [$user['id']]);
          if(!$rs){
              return '请到PC后台设置在线文案';
          }else if(count($rs)>1){
              $str = "您有".count($rs)."条在线文案 \n";
              foreach($rs as $k => $v){
                $k +=1;
                $str .= "回复3{$k}:{$v['title']} \n";
              }
              return $str;
          }else{
            return $this->zxwa($user,1);
          }
          break;
        case 'wytg':
          $img_path = $this->wytg($user);
          $media_id = $this->wxmedia($img_path,$user, true);
          return new Image($media_id);
          break;
        case 'lxkf':
          $rs = m('patch','c')->getData(['qun']);
          $str = explode("uploads",$rs['qun'][2]);
          $pic = "./uploads{$str[1]}";
          $media_id = $this->wxmedia($pic,$user, false);
          return new Image($media_id);
          break;
        default:
          return '天啊, 你点了什么';
          break;
      }
    }

    //在线文案
    public function zxwa($user, $sort=1){
      $sort -= 1;
      $rs  = $this->db->query('select * from zxwa where user_id =? order by sort desc, id asc', [$user['id']]);
      if(!isset($rs[$sort])){
        return '未找到,重新获取试试.';
      }
      return $rs[$sort]['content'];
    }


    //xcdy二维码
    public function xcdy($user, $sort=1){
      $sort -= 1;
      $rs  = $this->db->query('select * from xcdy where user_id =? order by sort desc, id asc', [$user['id']]);
      if(!isset($rs[$sort])){
        return '';
      }
      $id = $rs[$sort]['id'];
      $dir  = "./uploads/user/{$user['id']}/";
      if(is_file($dir."xcdy_{$id}.png")){
          return $dir."xcdy_{$id}.png";
      }
      com_mkdir($dir);
      $obj_img = $dir."xcdy_{$id}.png";
      #二维码
      $txt = url('xcdy/index/index',['id'=>$id]);
      $txt = urldecode($txt);
      $temp_qrcode = $dir."temp_qrcode.png";
      $qrCode = new QrCode($txt);
      $qrCode->setSize(350);
      $qrCode->setBackgroundColor(['r' => 249,'g' => 249,'b' => 249,'a' => 0,]);
      $qrCode->writeFile($temp_qrcode);
      #修改大小
      #模板
      $tpl_mb1 = "./uploads/template/mb1.png";

      $temp_avatar = com_fetch_pic($user['pic'], $dir."temp_avatar.png");
      $avatar_image = \think\Image::open($temp_avatar);
      $avatar_image->thumb(160,160)->save($temp_avatar);

      $image = \think\Image::open($tpl_mb1);
      $image->water($temp_avatar,[-1,120])->save($obj_img);
      $image->water($temp_qrcode,[-1,690])->save($obj_img);
      $image->text($user['username'],'./static/vendor/微软雅黑.ttf',20,'#000000',[-1,320])->save($obj_img);
      $image->text('扫码查看','./static/vendor/微软雅黑.ttf',18,'#adadad',[-1,400])->save($obj_img);
      $image->text($rs[$sort]['title'],'./static/vendor/微软雅黑.ttf',32,'#56b5a7',[-1,480])->save($obj_img);
      return $obj_img;
    }


    //微信名片二维码
    public function wxmp($user, $sort=1){
      $sort -= 1;
      $rs  = $this->db->query('select id from wxmp where user_id =? order by sort desc, id asc', [$user['id']]);
      if(!isset($rs[$sort])){
        return '';
      }
      $id = $rs[$sort]['id'];
      $dir  = "./uploads/user/{$user['id']}/";
      if(is_file($dir."wxmp_{$id}.png")){
          return $dir."wxmp_{$id}.png";
      }
      com_mkdir($dir);
      $obj_img = $dir."wxmp_{$id}.png";

      #二维码
      $txt = url('wxmp/index/index',['id'=>$id]);
      $txt = urldecode($txt);
      $temp_qrcode = $dir."temp_qrcode.png";
      $qrCode = new QrCode($txt);
      $qrCode->setSize(350);
      $qrCode->setBackgroundColor(['r' => 249,'g' => 249,'b' => 249,'a' => 0,]);
      $qrCode->writeFile($temp_qrcode);
      #修改大小
      #模板
      $tpl_mb1 = "./uploads/template/mb1.png";

      $temp_avatar = com_fetch_pic($user['pic'], $dir."temp_avatar.png");
      $avatar_image = \think\Image::open($temp_avatar);
      $avatar_image->thumb(160,160)->save($temp_avatar);

      $image = \think\Image::open($tpl_mb1);
      $image->water($temp_avatar,[-1,120])->save($obj_img);
      $image->water($temp_qrcode,[-1,690])->save($obj_img);
      $image->text($user['username'],'./static/vendor/微软雅黑.ttf',20,'#000000',[-1,320])->save($obj_img);
      $image->text('我的联系方式都在上面,赶快联系我把','./static/vendor/微软雅黑.ttf',18,'#adadad',[-1,400])->save($obj_img);
      $image->text('微信名片','./static/vendor/微软雅黑.ttf',32,'#56b5a7',[-1,480])->save($obj_img);
      return $obj_img;
    }


    //淘宝券二维码
    public function tbq($user){
      $dir  = "./uploads/user/{$user['id']}/";
      if(is_file($dir."tbq.png")){
          return $dir."tbq.png";
      }
      com_mkdir($dir);
      $obj_img = $dir."tbq.png";
      #二维码
      $txt = get_http_type() . DOMAIN . '/vtbk/index.html#/index?uid='.$user['id'];
      $txt = urldecode($txt);
      $temp_qrcode = $dir."temp_qrcode.png";
      $qrCode = new QrCode($txt);
      $qrCode->setSize(350);
      $qrCode->setBackgroundColor([
          'r' => 249,
          'g' => 249,
          'b' => 249,
          'a' => 0,]);
      $qrCode->writeFile($temp_qrcode);
      #修改大小
      // $image = \think\Image::open($temp_qrcode);
      // $image->thumb(350,350)->save($temp_qrcode);
      #模板
      $tpl_mb1 = "./uploads/template/mb1.png";
      $temp_avatar = com_fetch_pic($user['pic'], $dir."temp_avatar.png");
      $avatar_image = \think\Image::open($temp_avatar);
      $avatar_image->thumb(160,160)->save($temp_avatar);

      $image = \think\Image::open($tpl_mb1);
      $image->water($temp_avatar,[-1,120])->save($obj_img);
      $image->water($temp_qrcode,[-1,690])->save($obj_img);
      $image->text($user['username'],'./static/vendor/微软雅黑.ttf',20,'#000000',[-1,320])->save($obj_img);
      $image->text('嗨,这是我的淘宝券网站,可以领券购买淘宝商品','./static/vendor/微软雅黑.ttf',18,'#adadad',[-1,400])->save($obj_img);
      $image->text('淘宝券','./static/vendor/微软雅黑.ttf',32,'#56b5a7',[-1,480])->save($obj_img);
      return $obj_img;
    }


    //我要推广二维码
    public function wytg($user){
      $dir  = "./uploads/user/{$user['id']}/";
      if(is_file($dir."wytg.png")){
          return $dir."wytg.png";
      }
      com_mkdir($dir);
      $obj_img = $dir."wytg.png";
      #二维码
      $app = m('weixin','c')->getApp(c('api.wx_gzh_config')['myb']);
      $result = $app->qrcode->forever($user['id']);
      $txt    = $result['url'];
      $txt = urldecode($txt);


      $temp_qrcode = $dir."temp_qrcode.png";
      $qrCode = new QrCode($txt);
      $qrCode->setSize(350);
      $qrCode->setBackgroundColor([
          'r' => 249,
          'g' => 249,
          'b' => 249,
          'a' => 0,]);
      $qrCode->writeFile($temp_qrcode);
      #修改大小
      // $image = \think\Image::open($temp_qrcode);
      // $image->thumb(122,122)->save($temp_qrcode);
      #模板
      $tpl_mb1 = "./uploads/template/mb1.png";
      $temp_avatar = com_fetch_pic($user['pic'], $dir."temp_avatar.png");
      $avatar_image = \think\Image::open($temp_avatar);
      $avatar_image->thumb(160,160)->save($temp_avatar);

      $image = \think\Image::open($tpl_mb1);
      $image->water($temp_avatar,[-1,120])->save($obj_img);
      $image->water($temp_qrcode,[-1,690])->save($obj_img);
      $image->text($user['username'],'./static/vendor/微软雅黑.ttf',20,'#000000',[-1,320])->save($obj_img);
      $image->text('淘宝客,名片,宣传页,网站,商城等在线项目.','./static/vendor/微软雅黑.ttf',18,'#adadad',[-1,400])->save($obj_img);
      $image->text('邀请您关注蚂蚁帮在线','./static/vendor/微软雅黑.ttf',32,'#56b5a7',[-1,480])->save($obj_img);
      return $obj_img;
    }

    /**
    * 微信媒体
    * $path 本地路径
    * $user 用户信息
    * $is   是否永久素材
    **/
    public function wxmedia($path,$user=[], $is=true){
        $rs = $this->db->query("select * from wx_media where path=?", [$path],1);
        if(!$rs || $rs['end_time']<time()){
          if(isset($rs['end_time']) && $rs['end_time']<time()){
            $this->db->query("delete from wx_media where id=?", [$rs['id']]);
          }
          //重新传
          $app = m('weixin','c')->getApp(c('api.wx_gzh_config')['myb']);
          $result = $is ? $app->material->uploadImage($path) :  $app->media->uploadImage($path);
          $rs = [
            'path' => $path,
            'username' => $user['username'],
            'pic' => $user['pic'],
            'media_id' => $result['media_id'],
            'create_time' => time(),
            //'end_time' => $is ? strtotime("+10 year"): strtotime("+3 day"),
            'end_time' => $is ? strtotime("+10 year"): time(),
          ];
          $this->db->insert('wx_media', $rs);
        }
        return $rs['media_id'];
    }
}
